package com.zoweunion.mechanic.util.upload;

//import org.bytedeco.javacpp.opencv_core;
//import org.bytedeco.javacv.Java2DFrameConverter;
//import org.bytedeco.javacv.OpenCVFrameConverter;

import com.obs.services.model.ObsObject;
import com.zoweunion.mechanic.entity.ObsUtils;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.util.constants.Constants;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

//import org.bytedeco.javacpp.opencv_core.IplImage;
//import org.bytedeco.javacv.FFmpegFrameGrabber;
//import org.bytedeco.javacv.Frame;


/**
 * @Description:
 * @author: xukai
 * @date: 2018年2月7日 上午10:55:27
 */
public class UploadFile {

	public static UploadResult uploadImg(MultipartFile file, String uploadPath, User currentUser, Map<String, Object> reqMap)
			throws Exception {
		UploadResult uploadResult = null;
		if (file != null) {// 判断上传的文件是否为空
			String type = null;
			String pictureSource = null;
			if (reqMap != null && reqMap.get("type") != null) {
				pictureSource = reqMap.get("type").toString();
			}

			String fileName = file.getOriginalFilename();
			type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1)
					: null;
			if (type != null) {
				// 判断文件类型是否为空
				if (verificationImg(type)) {
					uploadResult = transferToImgNew(fileName, uploadPath, file, currentUser != null ? currentUser.getId() : null, pictureSource);
				} else {
					uploadResult = new UploadResult(0, "不是我们想要的文件类型,请按要求重新上传");
				}
			} else {
				uploadResult = new UploadResult(0, "文件类型为空");
			}
		} else {
			uploadResult = new UploadResult(0, "没有找到相对应的文件");
		}
		return uploadResult;
	}

	public static UploadResult uploadFiles(MultipartFile file, String uploadPath, User currentUser, Map<String, Object> reqMap)
			throws IOException {
		UploadResult uploadResult = null;
		if (file != null) {// 判断上传的文件是否为空
			String type = null;
			String pictureSource = null;
			if (reqMap.get("type") != null) {
				pictureSource = reqMap.get("type").toString();
			}

			String fileName = file.getOriginalFilename();
			type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1)
					: null;
			if (type != null) {
				// 判断文件类型是否为空
				if (verificationImg(type)) {
					uploadResult = transferToFilesNew(fileName, uploadPath, file, currentUser != null ? currentUser.getId() : null, pictureSource);
				} else {
					uploadResult = new UploadResult(0, "不是我们想要的文件类型,请按要求重新上传");
				}
			} else {
				uploadResult = new UploadResult(0, "文件类型为空");
			}
		} else {
			uploadResult = new UploadResult(0, "没有找到相对应的文件");
		}
		return uploadResult;
	}

	public static UploadResult uploadVideo(MultipartFile file, String uploadPath, HttpServletRequest request)
			throws IOException {
		UploadResult uploadResult = null;
		if (file != null) {// 判断上传的文件是否为空
			String type = null;
			String fileName = file.getOriginalFilename();
			type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())
					: null;
			if (type != null) {// 判断文件类型是否为空
				if (verificationVideo(type)) {
					uploadResult = transferToVideoNew(fileName, uploadPath, file);

				} else {
					uploadResult = new UploadResult(0, "不是我们想要的文件类型,请按要求重新上传");
				}
			} else {
				uploadResult = new UploadResult(0, "文件类型为空");
			}
		} else {
			uploadResult = new UploadResult(0, "没有找到相对应的文件");
		}
		return uploadResult;
	}

	public static UploadResult delFile(String path) {
		List<ObsObject> obsList = ObsUtils.selectObsObjects(path);
		if (obsList.size() >= 1) {
			ObsUtils.deleteObsObject(path);
			return new UploadResult(0, "删除成功");
		}else {
			return new UploadResult(1, "文件不存在");
		}

//		File file = new File("D:\\nginx-1.15.5/html/web-mechanic" + "/" + path);
//		// 路径为文件且不为空则进行删除
//		if (file.exists()) {
//			file.delete();
//			return new UploadResult(0, "删除成功");
//		} else {
//			return new UploadResult(1, "文件不能为空");
//		}
	}

	public static boolean verificationImg(String type) {
		if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())
				|| "PDF".equals(type.toUpperCase()) || "JPEG".equals(type.toUpperCase())) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean verificationVideo(String type) {
		if ("MP4".equals(type.toUpperCase()) || "AVI".equals(type.toUpperCase()) || "MPG".equals(type.toUpperCase())
				|| "MLV".equals(type.toUpperCase()) || "MOV".equals(type.toUpperCase())
				|| "RMVB".equals(type.toUpperCase())) {
			return true;
		} else {
			return false;
		}
	}

	public static UploadResult transferToImg(String fileName, String uploadPath, MultipartFile file, String userId, String pictureSource) throws IOException {
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        String path = null;// 文件路径
        // 项目在容器中实际发布运行的根路径
        String realPath = "D:\\nginx-1.15.5/html/web-mechanic";

		// File file = new File("D:\\static"+"/"+path);
        // String realPath="/opt/binhu/static";
        // 自定义的文件名称
        SimpleDateFormat sdFormatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileNamedate = sdFormatter1.format(nowTime) + "rondom" + new Random().nextInt(10000);
        String[] fileName1 = fileName.split("\\.");
        String lastFileName = fileNamedate + "." + fileName1[fileName1.length - 1];
        // 设置存放图片文件的路径
        String selectUploadPath = selectPath(uploadPath, userId, pictureSource);
        if (uploadPath.equals("oilLevelPictureUrl")) {
            path = realPath + "/" + selectUploadPath;
        } else {
            path = realPath + "/" + selectUploadPath + retStrFormatNowDate;
        }
        File dir = new File(path);
        if (!dir.exists()) {//
            dir.mkdirs();
        }
        System.out.println("存放文件的路径:" + path + "/" + lastFileName);
        File convFile = new File(path + "/" + lastFileName);
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();

        // 生成缩略图
//		Thumbnails.of(path + "/" + lastFileName).size(130, 100).toFile(path + "/thum_" + lastFileName);
        Thumbnails.of(path + "/" + lastFileName)
                .scale(1f)
                .outputQuality(0.1f)
                .toFile(path + "/thum_" + lastFileName);
        //给图片加水印 然后再转成缩略图
//        MyGaussianFilter.addWatermark(path + "/" + lastFileName,path + "/thum_" + lastFileName);
        if (uploadPath.equals("oilLevelPictureUrl")) {
            return new UploadResult(1, "上传成功",
                    selectUploadPath + lastFileName, selectUploadPath + "thum_" + lastFileName);
        } else {
            return new UploadResult(1, "上传成功",
                    selectUploadPath + retStrFormatNowDate + "/" + lastFileName, selectUploadPath + retStrFormatNowDate + "/thum_" + lastFileName);
        }
    }

	public static UploadResult transferToImgNew(String fileName, String uploadPath, MultipartFile file, String userId, String pictureSource) throws Exception {
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
		String retStrFormatNowDate = sdFormatter.format(nowTime);
		String path = null;// 文件路径
		// 项目在容器中实际发布运行的根路径
		// 自定义的文件名称
		SimpleDateFormat sdFormatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileNamedate = sdFormatter1.format(nowTime) + "rondom" + new Random().nextInt(10000);
		String[] fileName1 = fileName.split("\\.");
		String lastFileName = fileNamedate + "." + fileName1[fileName1.length - 1];
		// 设置存放图片文件的路径
		String selectUploadPath = selectPath(uploadPath, userId, pictureSource);
		if (uploadPath.equals("oilLevelPictureUrl")) {
			path =  selectUploadPath;
		} else {
			path =  selectUploadPath + retStrFormatNowDate;
		}
		//上传原始文件
		ObsUtils.uploadFile(path + "/" + lastFileName,file.getInputStream());
		File file1 = ObsUtils.multipartFileToFile(file);
		//压缩 缩略图
		ObsUtils.compress(file.getInputStream(),file1,5);
		InputStream inputStreams = new FileInputStream(file1);
		MultipartFile file2 = new MockMultipartFile(path + "/thum_" + lastFileName, inputStreams);
		//上传缩略图
		ObsUtils.uploadFile(path + "/thum_" + lastFileName,file2.getInputStream());
		//删除临时文件
		ObsUtils.delteTempFile(file1);

		if (uploadPath.equals("oilLevelPictureUrl")) {
			return new UploadResult(1, "上传成功",
					selectUploadPath + lastFileName, selectUploadPath + "thum_" + lastFileName);
		} else {
			return new UploadResult(1, "上传成功",
					selectUploadPath + retStrFormatNowDate + "/" + lastFileName, selectUploadPath + retStrFormatNowDate + "/thum_" + lastFileName);

		}
	}


	public static UploadResult transferToFiles(String fileName, String uploadPath, MultipartFile file, String userId, String pictureSource) throws IOException {

		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
		String retStrFormatNowDate = sdFormatter.format(nowTime);
		String path = null;// 文件路径
		// 项目在容器中实际发布运行的根路径
		String realPath = "D:\\nginx-1.15.5/html/web-mechanic";

//        File file = new File("D:\\static"+"/"+path);
		// String realPath="/opt/binhu/static";
		// 自定义的文件名称
		SimpleDateFormat sdFormatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileNamedate = sdFormatter1.format(nowTime) + "rondom" + new Random().nextInt(10000);
		String[] fileName1 = fileName.split("\\.");
		String lastFileName = fileNamedate + "." + fileName1[fileName1.length - 1];
		// 设置存放图片文件的路径

		String selectUploadPath = selectPath(uploadPath, userId, pictureSource);
		path = realPath + "/" + selectUploadPath + retStrFormatNowDate;
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		System.out.println("存放文件的路径:" + path + "/" + lastFileName);
		File convFile = new File(path + "/" + lastFileName);
		convFile.createNewFile();
		FileOutputStream fos = new FileOutputStream(convFile);
		fos.write(file.getBytes());
		fos.close();

		return new UploadResult(1, "上传成功",
				selectUploadPath + retStrFormatNowDate + "/" + lastFileName,"");
	}

	public static UploadResult transferToFilesNew(String fileName, String uploadPath, MultipartFile file, String userId, String pictureSource) throws IOException {

		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
		String retStrFormatNowDate = sdFormatter.format(nowTime);
		String path = null;// 文件路径
		// 自定义的文件名称
		SimpleDateFormat sdFormatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileNamedate = sdFormatter1.format(nowTime) + "rondom" + new Random().nextInt(10000);
		String[] fileName1 = fileName.split("\\.");
		String lastFileName = fileNamedate + "." + fileName1[fileName1.length - 1];
		// 设置存放图片文件的路径
		String selectUploadPath = selectPath(uploadPath, userId, pictureSource);
		path =  selectUploadPath + retStrFormatNowDate;

		//上传原始文件
		ObsUtils.uploadFile(path + "/" + lastFileName,file.getInputStream());
		System.out.println("存放文件的路径:" + path + "/" + lastFileName);
		return new UploadResult(1, "上传成功",
				selectUploadPath + retStrFormatNowDate + "/" + lastFileName,"");
	}



	public static UploadResult transferToImg(String fileName, String uploadPath, MultipartFile file) throws IOException {
		return transferToImg(fileName, uploadPath, file, null, null);
	}

	public static File convert(MultipartFile file) throws IOException {
		File convFile = new File(file.getOriginalFilename());
		convFile.createNewFile();
		FileOutputStream fos = new FileOutputStream(convFile);
		fos.write(file.getBytes());
		fos.close();
		return convFile;
	}


	public static UploadResult transferToVideo(String fileName, String uploadPath, MultipartFile file) throws IOException {
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
		String retStrFormatNowDate = sdFormatter.format(nowTime);
		String path = null;// 文件路径
		// 项目在容器中实际发布运行的根路径
		String realPath = "D:\\nginx-1.15.5/html/web-mechanic";
//        File file = new File("D:\\static"+"/"+path);
		// String realPath="/opt/binhu/static";
		// 自定义的文件名称
		SimpleDateFormat sdFormatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileNamedate = sdFormatter1.format(nowTime) + "rondom" + new Random().nextInt(10000);
		String[] fileName1 = fileName.split("\\.");
		String lastFileName = fileNamedate + "." + fileName1[fileName1.length - 1];
		// 设置存放图片文件的路径
		path = realPath + "/" + selectPath(uploadPath) + retStrFormatNowDate;
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		System.out.println("存放文件的路径:" + path + "/" + lastFileName);
		// 转存文件到指定的路径
		file.transferTo(new File(path + "/" + lastFileName));
		return new UploadResult(1, "上传成功", selectPath(uploadPath) + retStrFormatNowDate + "/" + lastFileName);
	}


	public static UploadResult transferToVideoNew(String fileName, String uploadPath, MultipartFile file) throws IOException {
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
		String retStrFormatNowDate = sdFormatter.format(nowTime);
		String path = null;// 文件路径
		// 自定义的文件名称
		SimpleDateFormat sdFormatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileNamedate = sdFormatter1.format(nowTime) + "rondom" + new Random().nextInt(10000);
		String[] fileName1 = fileName.split("\\.");
		String lastFileName = fileNamedate + "." + fileName1[fileName1.length - 1];
		// 设置存放图片文件的路径
		path = selectPath(uploadPath) + retStrFormatNowDate;

		//上传原始文件
		ObsUtils.uploadFile(path + "/" + lastFileName,file.getInputStream());
		System.out.println("存放文件的路径:" + path + "/" + lastFileName);
		return new UploadResult(1, "上传成功", selectPath(uploadPath) + retStrFormatNowDate + "/" + lastFileName);
	}

	public static void main(String[] args) {
		/*String realPath = "D:\\nginx-1.15.5/html/web-mechanic";
		String test = "http://my.zoweunion.com/upload/avatar/others/sdfasdfa.avi";
		System.out.println(test.indexOf("http://my.zoweunion.com/"));
		String strings = test.substring(23);
		String[] ss = strings.split("\\.");
		for (String s : ss) {
			System.out.println(s);
		}
		System.out.println(File.separator);*/
		String rootPath = "/Users/beck/Documents/work/zhlh/doc/debugger/avatar";
		String fileName = "img_index_0237-768x769.jpg";
		try{
			Thumbnails.of(rootPath + "/" + fileName)
					.scale(1f)
					.outputQuality(0.1f)
					.toFile(rootPath + "/thum_" + fileName);
		}catch (Exception e){
			System.out.println("原尺寸缩小报错");
			try{
				Thumbnails.of(rootPath + "/" + fileName)
						.size(130, 100)
						.toFile(rootPath + "/thum_" + fileName);
			}catch (Exception e2){
				e2.printStackTrace();
			}
		}
	}

	/**
	 * 获取图片质量系数
	 * @param filePath
	 */
	public static double thumbanilsQuality(String filePath) {
		return thumbanilsQuality(new File(filePath));
	}

	/**
	 * 获取图片质量系数
	 * @param file
	 */
	public static double thumbanilsQuality(File file) {
		double quality;
		long fileSize = file.length() / 1024;
		long m = 1024;
		if (fileSize <= 200) {
			quality = 1f;
		} else if (fileSize <= m) {
			quality = 0.4f;
		} else if (fileSize <= 5 * m) {
			quality = 0.2f;
		} else {
			quality = 0.1f;
		}
		return quality;
	}

	/*public static String fetchFrame(String videofile) {
		try {
			String realPath = "D:\\nginx-1.15.5\\html\\web-mechanic\\";
			String targetPath = videofile.split("\\.")[0];
			FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(realPath + videofile);
			ff.start();
			String rotate = ff.getVideoMetadata("rotate");
			int ffLength = ff.getLengthInFrames();
			Frame f;
			int i = 0;
			int index = 1;
			while (i < ffLength) {
				f = ff.grabImage();
				if (i == index) {
					if (null != rotate && rotate.length() > 1) {
						OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
						IplImage src = converter.convert(f);
						f = converter.convert(rotate(src, Integer.valueOf(rotate)));// 旋转图片
					}
					// targetFilePath = getImagePath(lpath, i);//根据视频路径生成缩略图存放路径
					doExecuteFrame(f, realPath + targetPath);// 获取缩略图
					break;
				}
				i++;
			}

//            String rotate =ff.getVideoMetadata("rotate");
//            Frame f;
//            int i = 0;
//            while (i <1) {
//                f =ff.grabImage();
//                IplImage src = null;
//                if(null !=rotate &&rotate.length() > 1) {
//                    OpenCVFrameConverter.ToIplImage converter =new OpenCVFrameConverter.ToIplImage();
//                    src =converter.convert(f);
//                    f =converter.convert(rotate(src, Integer.valueOf(rotate)));
//                }
//                doExecuteFrame(f,realPath+targetPath);
//                i++;
//            }
			ff.stop();
			return targetPath + ".jpg";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static IplImage rotate(IplImage src, int angle) {
		IplImage img = IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
		opencv_core.cvTranspose(src, img);
		opencv_core.cvFlip(img, img, angle);
		return img;
	}

	public static void doExecuteFrame(Frame f, String targerFilePath) {
		if (null == f || null == f.image) {
			return;
		}
		Java2DFrameConverter converter = new Java2DFrameConverter();
		String imageMat = "jpg";
		String FileName = targerFilePath + "." + imageMat;
		BufferedImage bi = converter.getBufferedImage(f);
		System.out.println("width:" + bi.getWidth());// 打印宽、高
		System.out.println("height:" + bi.getHeight());
		File output = new File(FileName);
		try {
			ImageIO.write(bi, imageMat, output);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/


	public static String selectPath(String uploadPath, String userId, String pictureSource) {
		String path = null;
		switch (uploadPath) {
			case "wxrecordfileurl":
				path = "upload/wxrecordfileurl/";
				break;
            case "oilLevelPictureUrl":
                path = "upload/oilLevel/"+ pictureSource + "/";
                break;
			default:
				path = "upload/avatar/user/";
				if (pictureSource != null) {
					path += Constants.UploadFileFolder.getFolder(pictureSource) + "/";
				} else {
					path = uploadPath + "/";
				}
				break;
		}
		return path;
	}

	public static String selectPath(String uploadPath) {
		return selectPath(uploadPath, null, null);
	}

}
